//
//  TestRNViewController.m
//  navigation
//
//  Created by user on 16/7/14.
//  Copyright © 2016年 Facebook. All rights reserved.
//

#import "TestRNViewController.h"
#import "RCTRootView.h"
#import "testwebViewController.h"
#import<SystemConfiguration/CaptiveNetwork.h>

@interface TestRNViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label0;
@property (weak, nonatomic) IBOutlet UITextField *text0;
@property (weak, nonatomic) IBOutlet UITextField *text1;
@property (weak, nonatomic) IBOutlet UITextField *text2;
@property (weak, nonatomic) IBOutlet UISwitch *swit;
@property (weak, nonatomic) IBOutlet UILabel *wifiName;

@property (weak, nonatomic) IBOutlet UIButton *lastButton;


@end

@implementation TestRNViewController


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //-shouldChangeCharactersInRange gets called before text field actually changes its text, that's why you're getting old text value. To get the text after update use:
    NSString * new_text_str = [textField.text stringByReplacingCharactersInRange:range withString:string];//变化后的字符串
    NSString *str0=self.text0.text;
    NSString *str1=self.text1.text;
    NSString *str2=self.text2.text;
    NSUserDefaults *de=[NSUserDefaults standardUserDefaults];
    
    if (textField ==self.text0) {
        str0=new_text_str;
        [de setObject:new_text_str forKey:@"text0"];
    }
    else     if (textField ==self.text1) {
        str1=new_text_str;
                [de setObject:new_text_str forKey:@"text1"];
    }
    else     if (textField ==self.text2) {
        str2=new_text_str;
        [de setObject:new_text_str forKey:@"text2"];
    }
    else  if (textField ==self.moduletext) {
        [de setObject:new_text_str forKey:@"moduletext"];
    }
    self.label0.text=[NSString stringWithFormat:@"%@%@%@",str0,str1,str2];
    return YES;
}
- (IBAction)changewifi:(id)sender {
    NSURL*url=[NSURL URLWithString:@"prefs:root=WIFI"];
    [[UIApplication sharedApplication] openURL:url];
}
- (IBAction)reset:(UIButton *)sender {
    self.text0.text=@"http://localhost:8081";
     self.text1.text=@"/index.ios.bundle";
     self.text2.text=@"?platform=ios&dev=true";
}

- (void)viewDidLoad {
  if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
  }
    [super viewDidLoad];
        NSUserDefaults *de=[NSUserDefaults standardUserDefaults];
    if ([[de objectForKey:@"text0"] length]) {
       self.text0.text=[de objectForKey:@"text0"];
    }
    if ([[de objectForKey:@"text1"] length]) {
        self.text1.text=[de objectForKey:@"text1"];
    }
    if ([[de objectForKey:@"text2"] length]) {
        self.text2.text=[de objectForKey:@"text2"];
    }
    if ([[de objectForKey:@"moduletext"] length]) {
        self.moduletext.text=[de objectForKey:@"moduletext"];
    }
  NSString *str0=self.text0.text;
  NSString *str1=self.text1.text;
  NSString *str2=self.text2.text;
      self.label0.text=[NSString stringWithFormat:@"%@%@%@",str0,str1,str2];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.wifiName.text=[self SSID];
  [self lastRNFile:nil];
}
- (NSString*)SSID
    {
        
    NSArray* ifs = (__bridge id)CNCopySupportedInterfaces();
        
            id info = nil;
        
            for (NSString* ifnam in ifs)
            
                {
                
                        info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
                
                        if (info && [info count])
                    
                                break;
                    }
        
            return info[@"SSID"];
        
        }
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  [self.view endEditing:YES];
}
- (IBAction)bian:(id)sender {
    testwebViewController*test=[[testwebViewController alloc]initWithNibName:@"testwebViewController" bundle:nil];
    [self.navigationController pushViewController:test animated:YES];
}
- (IBAction)loadjs:(id)sender {
    testwebViewController*test=[[testwebViewController alloc]initWithNibName:@"testwebViewController" bundle:nil];
    NSString *str0=_text0.text;
    NSString *str1=_text1.text;
    if ([str1 hasSuffix:@"bundle"]) {
        str1= [str1 stringByReplacingOccurrencesOfString:@"bundle" withString:@"js"];
    }
    test.jsurl=[NSString stringWithFormat:@"%@%@",str0,str1];
    test.preVC=self;
    [self.navigationController pushViewController:test animated:YES];
}
- (IBAction)replace:(id)sender {
    testwebViewController*test=[[testwebViewController alloc]initWithNibName:@"testwebViewController" bundle:nil];
    NSString *str0=_text0.text;
    NSString *str1=_text1.text;
    
    test.jsurl=[NSString stringWithFormat:@"%@%@",str0,str1];
    test.preVC=self;
    test.AutochangeMoudle=YES;
    [self.navigationController pushViewController:test animated:YES];
}

-(void)gotoRNWithUrl:(NSString *)url{
    NSURL *jsCodeLocation;
  
//   [[UIApplication sharedApplication] delegate].window.rootViewController=  [[TestRNViewController alloc]initWithNibName:@"TestRNViewController" bundle:nil];
//  return;
  jsCodeLocation=[NSURL URLWithString: url];
    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                        moduleName:self.moduletext.text
                                                 initialProperties:nil
                                                     launchOptions:nil];

    UIViewController *rootViewController = [UIViewController new];

    rootViewController.view = rootView;
//    [[UIApplication sharedApplication] delegate].window.rootViewController= rootViewController;
  [self presentViewController:rootViewController animated:YES completion:nil];
    UIButton *but=[[UIButton alloc]initWithFrame:CGRectMake(40, 20, 44, 33)];
    but.titleLabel.text=@"返回";
  [but setTitle:@"返回" forState:UIControlStateNormal];
  [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [but addTarget:self action:@selector(baketoself) forControlEvents:UIControlEventTouchUpInside];
  but.backgroundColor=[UIColor colorWithRed:50 green:150 blue:150 alpha:0.5];
    if (self.swit.isOn==YES) {
        [rootView addSubview:but];
    }
  
  
  NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:jsCodeLocation completionHandler:
                                ^(NSData *data, NSURLResponse *response, NSError *error) {
                                  if (error) {
                                  }
                                  else{
                                    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);
                                    NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
                                    
                                    NSString *FileName=[ourDocumentPath stringByAppendingPathComponent:@"lastindex.jsbundle"];
                                    [data writeToFile:FileName atomically:YES];
                                      NSUserDefaults *de=[NSUserDefaults standardUserDefaults];
                                    [de setObject:self.moduletext.text forKey:@"lastmoduletext"];
                                  }
                                }];
    [task resume];

}
- (IBAction)buttonin:(UIButton *)sender {
  NSString *str0=self.text0.text;
  NSString *str1=self.text1.text;
  NSString *str2=self.text2.text;
  NSUserDefaults *de=[NSUserDefaults standardUserDefaults];
    [de setObject:str0 forKey:@"text0"];


    [de setObject:str1 forKey:@"text1"];

    [de setObject:str2 forKey:@"text2"];

    [de setObject:self.moduletext.text forKey:@"moduletext"];

  self.label0.text=[NSString stringWithFormat:@"%@%@%@",str0,str1,str2];
  
  [self gotoRNWithUrl:self.label0.text];
  
   
}
- (IBAction)lastRNFile:(UIButton *)sender {
  NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);
  NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
  
  NSString *FileName=[ourDocumentPath stringByAppendingPathComponent:@"lastindex.jsbundle"];
  NSFileManager *fileManager = [NSFileManager defaultManager];
  BOOL ex=[fileManager fileExistsAtPath:FileName];
  if (sender==nil) {
      self.lastButton.userInteractionEnabled=ex;
      self.lastButton.enabled=ex;
    return;
  }
  if (ex==YES) {

    NSLog(@"File exists");
    NSUserDefaults *de=[NSUserDefaults standardUserDefaults];
  NSString *mod=[de valueForKey:@"lastmoduletext"];
  if(mod.length){
    self.moduletext.text=mod;
  }
  [self gotoRNWithUrl:FileName];
  }


}
-(void)baketoself{
//               [[UIApplication sharedApplication] delegate].window.rootViewController= self;
  [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
